package com.springboot.dense.util;

import com.springboot.dense.util.IPUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * CREATE BY funnyZpC ON 2018/5/3
 **/

public class IPInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //过滤ip,若用户在白名单内，则放行
        String ipAddress=IPUtils.getRealIP(request);
        if(!StringUtils.isNotBlank(ipAddress))
            return false;
        List<String> ips=new ArrayList<>();
        ips.add("100.89.84.87");
        ips.add("10.159.213.58");
        ips.add("10.203.145.83");
        System.out.println(ipAddress);
        System.out.println(ips);
        System.out.println(ips.contains(ipAddress));
        if(!ips.contains(ipAddress)){
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().append("<h1 style=\"text-align:center;\">抱歉，您没有权限访问!</h1>");
            return false;
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
